import { createStore } from 'vuex';
import axios from 'axios';

export default createStore({
    state: {
        token: localStorage.getItem('token') || '', // 初始化时从 localStorage 获取 token
        user: null, // 用户信息初始化为 null
    },
    mutations: {
        setToken(state, token) {
            state.token = token;
            localStorage.setItem('token', token); // 将 token 保存到 localStorage
        },
        setUser(state, user) {
            state.user = user;
        },
        resetAuthState(state) {  // 清理状态
            state.token = '';
            state.user = null;
            localStorage.removeItem('token'); // 清理 localStorage 中的 token
        }
    },
    actions: {
        async login({ commit }, credentials) {
            try {
                const response = await axios.post('/auth/login', credentials);
                commit('setToken', response.data.data.token); // 设置 token
                commit('setUser', response.data.data.user); // 设置用户信息
            } catch (error) {
                console.error('登录失败:', error);
                throw error; // 如果登录失败，抛出错误
            }
        },
        async fetchUserInfo({ commit }) {
            try {
                const response = await axios.get('/api/auth/current', {
                    headers: {
                        Authorization: `Bearer ${this.state.token}` // 使用 Vuex 中的 token
                    }
                });
                commit('setUser', response.data.data); // 更新用户信息
            } catch (error) {
                console.error('获取用户信息失败:', error);
                throw error; // 如果失败，抛出错误
            }
        }
    },
});